﻿Imports System.Web
Imports System.Web.SessionState
Imports Spring.Context.Support
Imports Spring.Context

Namespace Seguranca.Servico

    Public Class AutorizacaoModule
        Implements IHttpModule, IRequiresSessionState, IReadOnlySessionState

        Private _autenticacaoServico As IAutenticacaoServico
        Public Property AutenticacaoServico() As IAutenticacaoServico
            Get
                Dim ctx As IApplicationContext = ContextRegistry.GetContext()
                Return DirectCast(ctx("AutenticacaoServico"), IAutenticacaoServico)
            End Get
            Set(ByVal value As IAutenticacaoServico)
                _autenticacaoServico = value
            End Set
        End Property

        Private _autorizacaoServico As IAutorizacaoServico
        Public Property AutorizacaoServico() As IAutorizacaoServico
            Get
                Dim ctx As IApplicationContext = ContextRegistry.GetContext()
                Return DirectCast(ctx("AutorizacaoServico"), IAutorizacaoServico)
            End Get
            Set(ByVal value As IAutorizacaoServico)
                _autorizacaoServico = value
            End Set
        End Property

        Private _usuarioNaoAutenticadoUrl As String
        Public Property UsuarioNaoAutenticadoUrl() As String
            Get
                Dim _path As String = System.AppDomain.CurrentDomain.BaseDirectory & "Autorizacao.xml"
                Dim _xmlReader As New Xml.XmlTextReader(_path)
                Do
                    Try
                        If Not _xmlReader.Read() Then
                            Exit Do
                        End If
                    Catch ex As Exception
                        Throw New Exception("Erro lendo XML..." & ex.Message)
                    End Try
                Loop Until _xmlReader.LocalName.Equals("UsuarioNaoAutenticado")
                If _xmlReader.LocalName.Equals("UsuarioNaoAutenticado") Then
                    _usuarioNaoAutenticadoUrl = _xmlReader.GetAttribute("url")
                End If
                Return _usuarioNaoAutenticadoUrl
            End Get
            Set(ByVal value As String)
                _usuarioNaoAutenticadoUrl = value
            End Set
        End Property

        Private _usuarioNaoAutorizadoUrl As String
        Public Property UsuarioNaoAutorizadoUrl() As String
            Get
                Dim _path As String = System.AppDomain.CurrentDomain.BaseDirectory & "Autorizacao.xml"
                Dim _xmlReader As New Xml.XmlTextReader(_path)
                Do
                    Try
                        If Not _xmlReader.Read() Then
                            Exit Do
                        End If
                    Catch ex As Exception
                        Throw New Exception("Erro lendo XML .." & ex.Message)
                    End Try
                Loop Until _xmlReader.LocalName.Equals("UsuarioNaoAutorizado")
                If _xmlReader.LocalName.Equals("UsuarioNaoAutorizado") Then
                    _usuarioNaoAutorizadoUrl = _xmlReader.GetAttribute("url")
                End If
                Return _usuarioNaoAutorizadoUrl
            End Get
            Set(ByVal value As String)
                _usuarioNaoAutorizadoUrl = value
            End Set
        End Property

        Public Sub Dispose() Implements System.Web.IHttpModule.Dispose

        End Sub

        Public Sub Init(ByVal context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
            Dim _httpApplication As HttpApplication = context
            AddHandler _httpApplication.PostAcquireRequestState, New EventHandler(AddressOf Application_PostAcquireRequestState)
            AddHandler _httpApplication.PostMapRequestHandler, New EventHandler(AddressOf Application_PostMapRequestHandler)
        End Sub

        ''' <summary>
        ''' Substitui o HttpHandler por um que exige a carga de objetos de sessão.
        ''' </summary>
        Public Sub Application_PostMapRequestHandler(ByVal source As Object, ByVal e As EventArgs)
            Dim _httpApplication As HttpApplication = CType(source, HttpApplication)
            Dim _httpHandler As IHttpHandler = _httpApplication.Context.Handler
            '_httpApplication.Context.Handler = New SessaoGerenteHandler(_httpApplication.Context.Handler)
        End Sub

        ''' <summary>
        ''' Retorna o HttpHandler original e define o momento em que a autenticação
        ''' e a autorização podem ser feitas.
        ''' <see cref="AutorizacaoModule.Application_PostMapRequestHandler"/>
        ''' </summary>
        Public Sub Application_PostAcquireRequestState(ByVal source As Object, ByVal e As EventArgs)

            Throw New NotImplementedException("Em refactory")

            'Dim _httpApplication As HttpApplication = CType(source, HttpApplication)

            'If Not HttpContext.Current.Handler Is Nothing Then
            '    Dim _sessaoGerenteHandler As SessaoGerenteHandler = TryCast(HttpContext.Current.Handler, SessaoGerenteHandler)
            '    If Not _sessaoGerenteHandler Is Nothing Then
            '        HttpContext.Current.Handler = _sessaoGerenteHandler.OriginalHandler
            '    End If
            'End If

            'AutenticaUsuario(_httpApplication)
            'AutorizaRequest(_httpApplication)

        End Sub

        'Private Sub AutenticaUsuario(ByVal _httpApplication As HttpApplication)

        '    AutenticacaoServico.RecuperaContextoUsuario(HttpContext.Current)
        '    If AutenticacaoServico.UsuarioEstaAutenticado(HttpContext.Current) Then
        '        AutenticacaoServico.PersisteContextoUsuario(HttpContext.Current)
        '    Else
        '        TrataUsuarioNaoAutenticado(_httpApplication)
        '    End If

        'End Sub

        'Private Sub TrataUsuarioNaoAutenticado(ByVal _httpApplication As HttpApplication)
        '    _httpApplication.CompleteRequest()
        '    _httpApplication.Response.Redirect(UsuarioNaoAutenticadoUrl)
        'End Sub

        'Private Sub AutorizaRequest(ByVal _httpApplication As HttpApplication)
        '    If String.Compare(_httpApplication.Request.Path, UsuarioNaoAutorizadoUrl) <> 0 AndAlso _
        '    (_httpApplication.Request.ContentType = "" OrElse _httpApplication.Request.ContentType = "application/x-www-form-urlencoded") Then
        '        Dim _path As String = _httpApplication.Request.Path

        '        If _path.Contains(".aspx") Then
        '            _path = _path.Substring(0, _path.IndexOf(".aspx") + 5)
        '        End If
        '        If _path.Contains(".asmx") Then
        '            _path = _path.Substring(0, _path.IndexOf(".asmx") + 5)
        '        End If

        '        If Not (_path.EndsWith(".aspx") Or _path.EndsWith(".asmx")) Then
        '            Exit Sub
        '        End If

        '        If Not AutorizacaoServico.AutorizaRequest(_httpApplication.Request.Path) Then
        '            TrataUsuarioNaoAutorizado(_httpApplication)
        '        End If
        '    End If
        'End Sub

        'Private Sub TrataUsuarioNaoAutorizado(ByVal _httpApplication As HttpApplication)
        '    _httpApplication.CompleteRequest()
        '    _httpApplication.Response.Redirect(UsuarioNaoAutorizadoUrl)
        'End Sub

    End Class

End Namespace
